package edu.ntu.im.p2ptrade.msg.handle;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.util.zip.GZIPInputStream;

import edu.ntu.im.p2ptrade.P2PTrade;
import edu.ntu.im.p2ptrade.entity.User;
import edu.ntu.im.p2ptrade.msg.PMessage;
import edu.ntu.im.p2ptrade.msg.UserInfo;
import edu.ntu.im.p2ptrade.security.KeyManager;
import net.jxta.document.MimeMediaType;
import net.jxta.endpoint.ByteArrayMessageElement;
import net.jxta.endpoint.Message;
import net.jxta.endpoint.MessageElement;

public class UserInfoHandle implements PMessageHandle {

	public void handle(Message msg) {

		String name = null;
		if (msg.getMessageElement(P2PTrade.getInstance().getAppName(),
				PMessage.USERNAME) != null) {
			name = msg.getMessageElement(P2PTrade.getInstance().getAppName(),
					PMessage.USERNAME).toString();

		}
		if (!name.equals(P2PTrade.getInstance().getPeerName())) {
			User user = new User();
			user.setName(name);
			if (msg.getMessageElement(P2PTrade.getInstance().getAppName(),
					PMessage.USERDESC) != null) {
				String desc = msg.getMessageElement(
						P2PTrade.getInstance().getAppName(), PMessage.USERDESC)
						.toString();
				user.setDesc(desc);
			}
			if (msg.getMessageElement(P2PTrade.getInstance().getAppName(),
					PMessage.UNICKNAME) != null) {
				String nickName = msg
						.getMessageElement(P2PTrade.getInstance().getAppName(),
								PMessage.UNICKNAME).toString();
				user.setNickName(nickName);
			}
			if (msg.getMessageElement(P2PTrade.getInstance().getAppName(),
					PMessage.UPICURL) != null) {
				String photoURL = msg.getMessageElement(
						P2PTrade.getInstance().getAppName(), PMessage.UPICURL)
						.toString();
				user.setPhotoURL(photoURL);
			}
			if (msg.getMessageElement(P2PTrade.getInstance().getAppName(),
					PMessage.UTRUST) != null) {
				Boolean trustAble = Boolean.parseBoolean(msg.getMessageElement(
						P2PTrade.getInstance().getAppName(), PMessage.UTRUST)
						.toString());
				user.setTrustable(trustAble);
			}

			try {
				InputStream is = getInputStreamFromMessage(msg, P2PTrade
						.getInstance().getAppName(), UserInfo.PUBLIC_KEY);
				ObjectInputStream ois = new ObjectInputStream(is);
				Certificate pubkey = (Certificate) ois.readObject();
				if (KeyManager.getInstance().verify(pubkey)) {
					user.markAsTrustable();
				}
			} catch (Exception e) {
				e.printStackTrace();
				user.markAsTrustable();
			}
			PeerInfoRepository.getInstance().savePeer(user);
		}

	}

	public static InputStream getInputStreamFromMessage(Message message,
			String nameSpace, String elemName) throws IOException {
		InputStream result = null;
		MessageElement element = message.getMessageElement(nameSpace, elemName);
		if (null == element) {
			return null;
		}
		result = element.getStream();
		return result;
	}

}
